package org.luu.medicare.service;


import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.luu.medicare.common.Result;
import org.luu.medicare.entity.PageBean;
import org.luu.medicare.entity.TMedicine;
import org.luu.medicare.repository.TMedicineRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
@Slf4j
public class MedicineInfoService {
    private final TMedicineRepo medicineRepo;

    public Result<String> save(TMedicine medicine){
        medicineRepo.save(medicine);
        return Result.success();
    }

    public Result<String> deleteById(Integer id){
        Optional<TMedicine> medicine = medicineRepo.findById(id);
        if(medicine.isPresent()){
            medicineRepo.deleteById(id);
            return Result.success();
        }
        return Result.error("删除失败");
    }
    public Result<String> update(TMedicine medicine){
        Optional<TMedicine> oldMedicine = medicineRepo.findById(medicine.getId());
        if(oldMedicine.isPresent()){
            medicineRepo.save(medicine);
            return Result.success();
        }
        return Result.error("更新失败");
    }
    public Result<TMedicine> findById(Integer id){
        Optional<TMedicine> medicine = medicineRepo.findById(id);
        return medicine.map(Result::success).orElseGet(() -> Result.error("查询失败"));
    }

    public Result<PageBean<TMedicine>> page(int page,int pageSize,String name,String id){
        Pageable pageable = PageRequest.of(page - 1, pageSize);
        // 创建Specification用于动态查询
        Specification<TMedicine> spec = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (name != null && !name.isEmpty()) {
                predicates.add(criteriaBuilder.like(root.get("medName"), "%" + name + "%"));
            }
            if (id != null && !id.isEmpty()) {
                predicates.add(criteriaBuilder.like(root.get("medId"), "%" + id + "%"));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };
        // 执行分页查询
        Page<TMedicine> result = medicineRepo.findAll(spec, pageable);
        // 转换结果为PageBean
        PageBean<TMedicine> pageBean = new PageBean<>(result.getTotalElements(), result.getContent());
        // 日志记录
        log.info("查询药品，{},{}, {}", pageBean.getTotal(), result.getTotalElements(), result);
        return Result.success(pageBean);
    }

}
